package com.pospi.xstore.ui.vip_ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.dto.OrderBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.report.GoodsReportSearchActivity;
import com.pospi.xstore.ui.report.GoodsTopBeen;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import lib.kingja.switchbutton.SwitchMultiButton;

public class VipReportActivity extends BaseActivity {
    @Bind(R.id.total_je)
    TextView total_je;
    @Bind(R.id.bill_num)
    TextView bill_num;
    @Bind(R.id.switch_button)
    SwitchMultiButton switch_button;
    @Bind(R.id.tv_list_title)
    TextView tv_list_title;
    @Bind(R.id.bill_num_title)
    LinearLayout bill_num_title;
    @Bind(R.id.djsl_title)
    TextView djsl_title;

    private String count;
    private String je;
    private MyAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_goods_report);
        ButterKnife.bind(this);

        setMenuImage(R.drawable.icon_search_white);
        tv_list_title.setText("消费总额");
        djsl_title.setText("商品数量");
        setTitle("消费记录");
        init();
        downStore();
        downSup();
        downCus();
    }
    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        Intent intent = new Intent(this, VipSalesSearchActivity.class);
        startActivity(intent);

    }



    private void init() {
        switch_button.setText("今天","昨天","近三天","近七天","近一月");
        switch_button.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                switch (position) {
                    case 0:
                        startrq = GetData.getAnyTime(0);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 1:
                        startrq = GetData.getAnyTime(1);
                        endrq = GetData.getAnyTime(1);
                        searchBillfast();
                        break;
                    case 2:
                        startrq = GetData.getAnyTime(3);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 3:
                        startrq = GetData.getAnyTime(7);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 4:
                        startrq = GetData.getAnyTime(30);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                }
            }
        });
        tv_list_title.setText("没有查询到数据");

        ListView bill_list = (ListView) findViewById(R.id.list_bill);
        adapter = new MyAdapter();
        bill_list.setAdapter(adapter);

        switch_button.clearSelection();
        startrq = getIntent().getStringExtra("startrq");
        endrq = getIntent().getStringExtra("endrq");
        market = getIntent().getStringExtra("market");
        vipid = getIntent().getStringExtra("vipid");
        searchBillfast();

    }

    private String market = "";
    private String vipid = "";
    private String custid;
    private String brandid;
    private String num;
    private String barcode;
    private String name;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switch_button.clearSelection();
        startrq = intent.getStringExtra("startrq");
        endrq = intent.getStringExtra("endrq");
        market = intent.getStringExtra("market");
        vipid = intent.getStringExtra("vipid");
        searchBillfast();

    }

    private class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return topBeens.size();
        }

        @Override
        public Object getItem(int i) {
            return topBeens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder ;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(VipReportActivity.this).inflate(R.layout.vipgoods_item, null);
                holder.xh = view.findViewById(R.id.tv_xh);
                holder.name = view.findViewById(R.id.tv_name);
                holder.xsje = view.findViewById(R.id.tv_xsje);
                holder.xssl = view.findViewById(R.id.tv_xssl);
                holder.mle = view.findViewById(R.id.tv_xsmle);
                holder.mlr = view.findViewById(R.id.tv_xsmlr);
                holder.tv_time = view.findViewById(R.id.tv_time);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            VipGoodsBeen been = topBeens.get(i);
            holder.xh.setText(i+1+"");
            holder.name.setText(been.getGoodsname());
            holder.xsje.setText(been.getXsjje());
            holder.xssl.setText(been.getMarketname());
            holder.mle.setText(been.getSl());
            holder.mlr.setText(been.getType());
            holder.tv_time.setText(been.getSendrq());
            return view;
        }
        class Holder{
            TextView xh;
            TextView name;
            TextView xsje;
            TextView xssl;
            TextView mle;
            TextView mlr;
            TextView tv_time;

        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    if (topBeens.size() == 0) {
                        setbill(false);
                        adapter.notifyDataSetChanged();
                    } else {
                        setbill(true);
                        adapter.notifyDataSetChanged();
                    }

                    break;
                case 2:

                    break;
                case 3:
                    close();
                    Toast.makeText(VipReportActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                    break;
                case 4:

                    break;
            }

        }
    };
    private void setbill(boolean o){
        if (o) {
            bill_num_title.setVisibility(View.VISIBLE);
            tv_list_title.setText("总消费额");
            total_je.setText(je);
            bill_num.setText("" + count );
        } else {
            tv_list_title.setText("没有查询到数据");
            total_je.setText("");
            bill_num.setText("");
            bill_num_title.setVisibility(View.INVISIBLE);
            topBeens.clear();
            adapter.notifyDataSetChanged();
        }

    }


    //下载门店
    private void downStore() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.STORE_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    //下载供应商
    private void downSup() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getsupplier");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.SUP_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    //下载客员工
    private void downCus() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getperson");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    SPHelper.getInstance().putString(Constant.CUS_LIST, result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }

    private String startrq = GetData.getAnyTime(0);
    private String endrq = GetData.getAnyTime(0);

    private void searchBillfast() {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "pos.mreport");
        params.put("fun", "findvipxfjl");

        params.put("vipid", vipid);
        params.put("startrq", startrq);
        params.put("endrq", endrq);
        params.put("market", market);

        Log.i("vipsf",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("vipsf", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    Log.i("login", jsonObject.getString("errMsg"));
                    JSONArray result = jsonObject.getJSONArray("result");
                    getResult(result);
                    count = jsonObject.getJSONObject("sumrow").getString("sum_sl");
                    je = jsonObject.getJSONObject("sumrow").getString("sum_xsjje");
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    List<VipGoodsBeen> topBeens = new ArrayList<>();
    private void getResult(JSONArray result) {
        topBeens.clear();
        List<VipGoodsBeen> mBeens = new Gson().fromJson(result.toString(), new TypeToken<List<VipGoodsBeen>>() {
        }.getType());
        topBeens.addAll(mBeens);
    }

}
